package com.cskaoyan.market.controller.Admin;

import com.cskaoyan.market.annotation.Log;
import com.cskaoyan.market.db.domain.MarketAdmin;
import com.cskaoyan.market.db.domain.MarketPermission;
import com.cskaoyan.market.db.domain.MarketRole;
import com.cskaoyan.market.service.admin.MarketAdminService;
import com.cskaoyan.market.service.admin.MarketPermissionService;
import com.cskaoyan.market.service.admin.MarketRoleService;
import com.cskaoyan.market.shiro.MarketToken;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2024/5/3 16:26
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {

    @Autowired
    MarketPermissionService marketPermissionService;
    
    @Autowired
    MarketRoleService marketRoleService;
    @Autowired
     MarketAdminService adminService;
    @Autowired
    SecurityManager securityManager;
    //登录的流程：获取接收用户的请求参数信息；校验，系统中进行比对(调用service、mapper)，根据比对的结果返回一个回执信息

    @PostMapping("/login")
    public Object login(@Valid @RequestBody MarketAdmin marketAdmin1, HttpServletRequest request) {
        String username = marketAdmin1.getUsername();
        String password = marketAdmin1.getPassword();
        String optionIp = request.getRemoteAddr();
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument();
        }
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketToken token = new MarketToken(username, password, "admin");
        try {
            subject.login(token);
            MarketAdmin marketAdmin =(MarketAdmin) subject.getPrincipal();
            Session session = subject.getSession();
            //登录成功，往session域写入数据，但是随即你便会发现一个问题，那就是无论怎么获取，始终获取不到session域里面的数据
            //todo 记录用户登录成功 logService.addLog()
            //用户名、密码匹配------做到和公网具有相同的返回结果
            //设置响应体 字符流  字节流
            Map<String, Object> data = new HashMap<>();
            Map<String, String> adminInfo = new HashMap<>();
            adminInfo.put("nickName", marketAdmin.getUsername());
            adminInfo.put("avatar", marketAdmin.getAvatar());
            data.put("adminInfo", adminInfo);
            //token其实就是session域的编号
            session.setAttribute("admin", marketAdmin);
            session.setAttribute("ip",optionIp);
            data.put("token", session.getId());

            adminService.login(marketAdmin);
            return ResponseUtil.ok(data);

        }catch (Exception e){
            adminService.login(null);
            return ResponseUtil.fail(404, "用户名密码不匹配");
        }
    }
@PostMapping("logout")
public Object logout()  {
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    Session session = subject.getSession();
        if (session != null) {
            adminService.logout(session);
            session.removeAttribute("admin");
            return ResponseUtil.ok();
        }else {
            adminService.logout(null);
            return ResponseUtil.fail(404, "请先登录");
        }
    }
    @GetMapping("info")
    public Object info() {
        //当前结果需要返回上述的json字符串
        //从session域里面获取
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MarketAdmin admin = (MarketAdmin) session.getAttribute("admin");
        Map<String,List<String>> permissionsAndRoles=marketPermissionService.getPermissionsAndRoles(admin.getRoleIds());
        Map<String, Object> data = new HashMap<>();
        //roles和perms是关于权限相关的，大家项目一不用去操心，直接固定写死，让接口通过即可
        data.put("roles", permissionsAndRoles.get("roles"));
        data.put("name", admin.getUsername());
        data.put("perms", permissionsAndRoles.get("perms"));
        data.put("avatar", admin.getAvatar());
        Object ok = ResponseUtil.ok(data);
        return ok;
    }
}
